<?php
namespace Home\Controller;
use Think\Controller;

class CartController extends \Common\Controller\UserController {
    //购物车列表
    public function index() {
        $userid = session('userid');

        $I=M('integral');
        $int=$I->where('userid='.$userid)->find();
        $this->assign('int',$int);

        $other = empty($_REQUEST['o'])?0:$_REQUEST['o'];
        $page = empty($_REQUEST['page'])?1:$_REQUEST['page'];
        $pagesize =10;

        $sqlw=' 1 = 1 ';

        $sqlw.=' and userid='.$userid;

        $room = M('cart');
        //$info = $room->where("status=0")->limit(($page-1)*$page_size,$page_size)->select();
        //$info = $room->join('left join tm_member on tm_task.memberid = tm_member.memberid ')->limit(($page-1)*$page_size,$page_size)->select();
        // $memberid=session('userid');

        $sql = 'select count(*) as total from tm_cart where '.$sqlw;

        $query = $room -> query($sql);

        $pageurl='/user/cart.html?';


        $count = $query[0]['total'];

        $this->assign('room', $room->order('id desc')->where($sqlw)->limit(($page-1)*$pagesize,$pagesize)->select());

        $this->assign('total',$count);

        if($count%$pagesize==0)
            $this->assign('count',$count/$pagesize);
        else {
        	$this->assign('count',(int)floor($count/$pagesize)+1);
        }

        $this->assign('page',$page);

        $this->assign('pageurl', $pageurl);
        $this->assign('pagesize', $pagesize);

		$this->assign('add', M('user_address') -> where('userid=' . $userid) -> order('def desc') -> select());
		$this->assign('user', M('user') -> where('id=' . $userid)->find());

        $this->display();

    }

	//加入购物车
    public function docart() {
    	$productId = I('get.id');
    	$userid = session('userid');

    	$Cart = M('cart');
    	$where = 'userid = ' . $userid . ' AND productid = ' . $productId;
    	if($Cart -> where($where) -> find()) {
    		$Cart -> where($where) -> setInc('number');
    	} else {
    		$product = M('product') -> where('id=' . $productId) -> find();
    		$Cart -> add(array(
    			'userid' => $userid,
	            'productname' => $product['productname'],
	            'price' => $product['price'],
	            'number' => 1,
	            'productid' => $product['id'],
	            'createtime' => time(),
	            'pic' => $product['pic'],
    		));
    	}
    	echo "<script>alert('已加入购物车！');history.go(-1);</script>";
        die();
    }
   
    
    //清空购物车
    public function deletecart() {
        M('cart') -> where('userid = ' . session('userid')) -> delete();
        echo '<script>alert("购物车已清空！");location.href="/user/cart.html";</script>';
        die();
    }
	
	//提交购物车订单
	public function docartorder() {
		if(IS_POST) {
			$data = I('post.');
			$userid = session('userid');
			
			// 判断支付密码
			$User = M('user') -> field('paypassword') -> where('id = ' . $userid) -> find();
    		if(!(new \Think\PasswordHash()) -> CheckPassword(md5($data['paypassword']), $User['paypassword'])) {
    			echo"<script>alert('支付密码错误！');history.go(-1);</script>";
    			exit;
    		}

			$Integral = M('integral');
			$IntegralD = $Integral -> where('userid='.$userid) -> find();
			if($IntegralD['integral1'] + $IntegralD['integral' . $data['pay']] < $data['totalprice']) {
				echo '<script>alert("余额不足，请充值！");history.go(-1);</script>';
	            die();
			}

			$numberTotal = 0;
			$priceTotal = 0;
			$Cart = M('cart');
			$products = array();
			$orderId = 0;
			$delCartIds = '';
			foreach($data['carts'] as $k => $cart) {
				if(isset($cart['id']) && $k == $cart['id']) {
					$numberTotal += $cart['number'];
					$priceTotal  += $cart['total'];
					$p = $Cart -> where('id = ' . $cart['id']) -> find();
					$products[] = array(
						'productid' => $p['id'],
						'orderid' => &$orderId,
						'number' => $cart['number'],
						'price' => $cart['total'],
						'productname' => $p['productname'],
						'pic' => $p['pic'],
					);
					$delCartIds .= $cart['id'] . ',';
				}
			}

			\Think\Db::startTrans();
			try {
				// 判断动态，动态不足时使用静态
				if($IntegralD['integral' . $data['pay']] < $data['totalprice']) {
					if($IntegralD['integral' . $data['pay']] > 0) {
						if(!$Integral -> where('userid=' . $userid) -> save(array('integral' . $data['pay'] => 0))) {
							throw new \Exception('订单生成失败!');
						}
	
						if(!$this -> payHistory($userid, '购买商品', $IntegralD['integral' . $data['pay']], time(), 0, $data['pay'])) {
							throw new \Exception('订单生成失败!');
						}

						$data['totalprice'] = $data['totalprice'] - $IntegralD['integral' . $data['pay']];
					}

					if(!$Integral -> where('userid=' . $userid) -> setDec('integral1', $data['totalprice'])) {
						throw new \Exception('订单生成失败!');
					}

					if(!$this -> payHistory($userid, '购买商品', $data['totalprice'], time(), 0, 1)) {
						throw new \Exception('订单生成失败!');
					}
				} else {
					if(!$Integral -> where('userid=' . $userid) -> setDec('integral' . $data['pay'], $data['totalprice'])) {
						throw new \Exception('订单生成失败!');
					}

					if(!$this -> payHistory($userid, '购买商品', $data['totalprice'], time(), 0, $data['pay'])) {
						throw new \Exception('订单生成失败!');
					}
				}
	
				$orderId = M('order') -> add(array(
					'userid' => session('userid'),
					'orderid' => $this -> Createorderid(2),
					'productname' => '',
					'price' => $priceTotal,
					'number' => $numberTotal,
					'createtime' => time(),
					'status' => 2,
					'pay' => $data['pay']
				));
	
				if(!$orderId) {
					throw new \Exception('订单生成失败!');
				}
				
				if(!M('order_address') -> add(array(
					'orderid' => $orderId,
					'mobile'  => $data['mobile'],
					'contact' => $data['realname'],
					'tel'     => '',
					'post'    => '',
					'address' => $data['address'],
				))) {
					throw new \Exception('订单生成失败!');
				};
	
				if(!M('order_product') -> addAll($products)) {
					throw new \Exception('订单生成失败!');
				}
	
				if(!$Cart -> where('id IN (' . substr($delCartIds, 0, -1) . ')') -> delete()) {
					throw new \Exception('订单生成失败!');
				}
	
				\Think\Db::commit();
			} catch (\Exception $e) {
				\Think\Db::rollback();
				echo '<script>alert("' . $e -> getMessage() . '");history.go(-1);</script>';
				exit;
			}
			echo"<script>alert('订单提交成功，请等候发货！');location.href='/user/order.html';</script>";
			exit;
		}
	}

	//生成20位订单号
    private function Createorderid($t) {
        $orderid= date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(100, 999);
        //1充值　２订单支付　３注册支付
        return $orderid . $t;
    }

    private function payHistory($userid,$title,$price,$createtime,$status,$gotegary) {
        return M('income') -> add(array(
            'userid' => $userid,
            'title' => $title,
            'price' => $price,
            'createtime' => $createtime,
            'status' => $status,
            'gotegary' => $gotegary,
        ));
    }
}
?>